﻿using System.Collections.Generic;
using System.Linq;
using LingDong.IndexEntities.Dictionary;
using LingDong.IndexEntities.Document;
using LingDong.IndexReader;

namespace LingDong.QueryCore
{
    internal class Ranker
    {
        /// <summary>
        /// Get query result doc list
        /// </summary>
        /// <param name="index"></param>
        /// <param name="allInvertedList"></param>
        /// <returns></returns>
        internal static List<ParsedDocumentEntity> GetResultDocList(Index index, List<Dictionary<int, InvertedListEntity>> allInvertedList)
        {
            List<ParsedDocumentEntity> docList = new List<ParsedDocumentEntity>();
            int allInvertedListCount = allInvertedList.Count;
            if (allInvertedListCount == 0)
            {
                return docList;
            }

            // sort to speed up intersect
            allInvertedList = allInvertedList.OrderBy(array => array.Values.Count).ToList();

            // select docs which contains all query words
            InvertedListEntity[] intersectArray = allInvertedList[0].Values.ToArray();
            for (int i = 1; i < allInvertedListCount; i++)
            {
                intersectArray = intersectArray.Intersect(allInvertedList[i].Values.ToArray(), 
                                                          new InvertedListEntityComparer()).ToArray();
            }

            List<int> docIDList = intersectArray.Select<InvertedListEntity, int>(p => p.DocID).ToList();
            foreach (int id in docIDList)
            {
                ParsedDocumentEntity doc = index.GetParsedDocument(id);
                docList.Add(doc);
            }

            // sort by page rank
            docList = docList.OrderByDescending(doc => doc.Rank).ToList();

            return docList;
        }
    }
}
